package com.mytomcat.catalina.valve;

import javax.servlet.http.HttpServlet;

import com.mytomcat.catalina.request.Request;
import com.mytomcat.catalina.response.Response;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 标准Wrapper阀
 *
 * @author supu
 * @date 2019-04-19 17:27
 **/
public class StandardWrapperValve extends ValveBase {
    private static final Logger LOGGER = LoggerFactory.getLogger(StandardWrapperValve.class);

    @Override
    public void invoke(Request request, Response response) {
        LOGGER.info("StandardWrapperValve invoke");

        Map<String,String> servletNameMap = request.getWrapper().getServletNameMap();

        String servletPath = request.getServletPath();
        String servletName = "default";
        if(servletPath.endsWith(".jsp") || servletPath.endsWith(".jspx")){
            servletName = "jsp";
        }

        try {
            // 根据请求URL获取对应的servlet
            Class<HttpServlet> httpServletClass = (Class<HttpServlet>)Class.forName(servletNameMap.get(servletName));
            HttpServlet servlet = httpServletClass.newInstance();
            servlet.service(request, response);

            response.write(servletName +" 请求");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
